/*
 * @Author: yangzonglong
 * @Date: 2021-07-09 13:20:24
 * @version: v1.0.0
 * @Descripttion: table input 控制器
 * @LastEditors: 871387321@qq.com 871387321@qq.com
 * @LastEditTime: 2023-11-21 16:01:31
 * @Auditor:
 */
import React, { useCallback, useMemo, useRef } from 'react';
import { Select } from '@library';
import CommonController from '../CommonController';
import { Form, Input, Checkbox, InputNumber } from 'antd';
import update from 'immutability-helper';
import InitialValue from './../../components/InitialValue';
import { IProps } from '../config';
import { regExpSource } from '../../../config';

const ftStyle = { marginBottom: '8px' };
const fieldNames = { label: 'label', value: 'value' };
const linkType = ['dataLink', 'dataLinkCombox', 'dataLinkComBox'];
const InputController = ({
  tableProps,
  required,
  placeholder,
  placeholderEn,
  checkRule,
  originalIndex,
  columns,
  dataIndex,
  width,
  precision,
  print,
  step,
  max,
  min,
  formatterMoney,
  hideArrow,
  showFiled,
  title,
  titleEn,
  textAlign,
  bindName,
  initialValue,
  disabled,
  exportFlag,
  setCurColumn,
  changeColumnOptions,
  changeControlProps,
  fontSize,
  fontWeight,
  backgroundColor,
  color,
  customizeStyleFlag
}: IProps) => {
  const dataObj = useRef({});

  const showComponentsArray = useMemo(() => {
    let _dataObj: any = {};
    let _list = columns?.filter((item: any) => linkType.includes(item.type));

    _list?.forEach((element: any) => {
      const obj = {};
      const extraFieldName = element?.options?.extraFieldName || []; // 扩展数据
      const filedShowName = element.options?.filedShowName || []; // 关联数据 及模态框显示
      let showFieldName = element.options?.showFieldName || []; // 显示数据

      // 之前老的表单是string
      if(typeof showFieldName === 'string') {
        showFieldName = [{ value: showFieldName, label: showFieldName }]
      }

      const arr = [...extraFieldName, ...showFieldName, ...filedShowName];
      
      // 将原始字段处理成k,v的形式，方便找出对应中文
      const fieldNamesMap = element.options?.fieldNames?.reduce((next: Record<string, string>, cur: { label: string; value: string }) => {
        next[cur.value] = cur.label;
        return next
      }, {}) || {};

      arr.forEach(item => {
        if(typeof item === 'string') {
          obj[item] = { value: item, label: fieldNamesMap[item] }
        }else {
          obj[item.value] = { value: item.value, label: fieldNamesMap[item.value] }
        }
      });
      
      _dataObj[element.dataIndex!] = Object.values(obj);
    });

    dataObj.current = _dataObj;
    return _list?.map((item: any) => ({ label: item?.title, value: item?.dataIndex, id: item?.key }));
  }, [columns]);

  const onChange = useCallback(
    (value: string) => {
      changeColumnOptions('initialValue', value, originalIndex);
    },
    [changeColumnOptions, originalIndex]
  );

  const onChangeKey = useCallback(
    (value, key) => {
      changeColumnOptions(key, value, originalIndex);
    },
    [changeColumnOptions, originalIndex]
  );

  const onChangeColumnOptions = useCallback(
    (e: any, k: string, isChecked?: boolean) => {
      changeColumnOptions(k, isChecked ? e.target.checked : e.target.value, originalIndex);
    },
    [changeColumnOptions, originalIndex]
  );

  const _changeControlProps = useCallback(
    (e: any, k: string, isChecked?: boolean) => {
      changeControlProps(
        'tableProps',
        {
          ...tableProps,
          columns: update(columns!, {
            [originalIndex!]: {
              [k]: {
                $set: isChecked ? e.target.checked : e.target.value,
              },
            },
          }),
        },
        true
      );

      setCurColumn?.({ ...columns![originalIndex!], originalIndex, [k]: isChecked ? e.target.checked : e.target.value });
    },
    [changeControlProps, columns, originalIndex, setCurColumn, tableProps]
  );

  return (
    <CommonController
      showTextAlign
      onChangeControlProps={_changeControlProps}
      onChangeColumnOptions={onChangeColumnOptions}
      {...{ title, titleEn, dataIndex, width, required, print, disabled, exportFlag, fontSize, fontWeight, backgroundColor, color, textAlign, customizeStyleFlag }}
    >

      <Form.Item label="提示">
        <Input onChange={(e) => onChangeKey(e.target.value, 'placeholder')} value={placeholder} />
      </Form.Item>

      <Form.Item label="英文提示">
        <Input onChange={(e) => onChangeKey(e.target.value, 'placeholderEn')} value={placeholderEn} />
      </Form.Item>

      <Form.Item label="校验规则">
        <Select
          value={checkRule as string}
          allowClear
          dataSource={regExpSource}
          onClear={() => onChangeKey(undefined, 'checkRule')}
          onSelect={(e: any) => {
            onChangeKey(e, 'checkRule',);
          }}
          fieldNames={fieldNames}
          url=""
          placeholder="请选择校验规则"
        />
      </Form.Item>

      <Form.Item label="关联已有数据">
        <Form.Item>
          <Select
            style={ftStyle}
            value={bindName}
            allowClear
            onClear={() => changeColumnOptions('', { bindName: undefined, showFiled: undefined }, originalIndex)}
            onSelect={(e: any) => changeColumnOptions('', { bindName: e, showFiled: undefined }, originalIndex)}
            dataSource={(showComponentsArray || []) as any[]}
            fieldNames={fieldNames}
            url=""
            placeholder="请选择组件"
          />
        </Form.Item>
        <Form.Item>
          <Select
            style={ftStyle}
            value={showFiled}
            onSelect={(e: any) => changeColumnOptions('showFiled', e, originalIndex)}
            dataSource={dataObj.current?.[bindName!]}
            fieldNames={fieldNames}
            url=""
            placeholder="请选择显示字段"
          />
        </Form.Item>
      </Form.Item>

      <InitialValue value={initialValue} onChange={onChange} />

      <Form.Item className="antd-form-item-row" label="是否显示成金额">
        <Checkbox onChange={(e) => onChangeKey(e.target.checked, 'formatterMoney')} checked={formatterMoney} />
      </Form.Item>

      <Form.Item className="antd-form-item-row" label="隐藏增减键">
        <Checkbox onChange={(e) => onChangeKey(e.target.checked, 'hideArrow')} checked={hideArrow} />
      </Form.Item>


      <Form.Item label='最小值'>
        <InputNumber
          onChange={(e) => onChangeKey(e, 'min')} value={min}
        />
      </Form.Item>

      <Form.Item label='最大值'>
        <InputNumber
          onChange={(e) => onChangeKey(e, 'max')} value={max}
        />
      </Form.Item>

      <Form.Item label='步数' tooltip='加减步数'>
        <InputNumber
          onChange={(e) => onChangeKey(e, 'step')} value={step}
        />
      </Form.Item>

      <Form.Item label='数值精度' tooltip='保留几位小数'>
        <InputNumber
          onChange={(e) => onChangeKey(e, 'precision')} value={precision}
        />
      </Form.Item>

    </CommonController>
  );
};

export default InputController;
